# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _


class ProductTemplate(models.Model):
    _inherit = 'product.template'

    def get_bom_structure(self, res_product, product_id, level=0, index=0):
        """递归获取BOM层级结构"""
        bom = self.env['mrp.bom'].search([
            ('product_tmpl_id', '=', product_id.product_tmpl_id.id),
            ('type', '=', 'normal')
        ], limit=1)
        structure = []
        sub_semi_boms = bom.bom_line_ids.filtered(lambda x: x.product_id.bom_ids)
        line_count = len(sub_semi_boms)
        component = {
            'level': level,
            'index': index,
            'bom_id': bom.id,
            'line_count': line_count
        }
        structure.append(component)
        index = 1
        for line in sub_semi_boms:
            structure.extend(self.get_bom_structure(res_product, line.product_id, level + 1, index))
            index += 1
        return structure

    @api.model
    def recursive_bom_lines(self, product_id):
        result = {}
        boms = self.env['mrp.bom'].search([
            ('product_tmpl_id', '=', product_id.product_tmpl_id.id),
            ('type', '=', 'normal')
        ])
        if len(boms) > 1:
            result[product_id] = boms
        for bom_line in boms.bom_line_ids:
            product = bom_line.product_id
            sub_result = self.recursive_bom_lines(product)
            if sub_result:
                result.update(sub_result)
        return result
